<?php
namespace Home\Controller;
use Think\Controller;
use Think\Model;
class DoctorAuthController extends Controller
{
    protected function echoJson($arr)
    {//内部函数
        echo json_encode($arr);
    }

    //======================APP注册信息====================================
    public function register()
    {
        if (I("request.logname") != '' && I("request.password") != '') {
            $logname = I("request.logname");
            if(!preg_match('/^[_0-9a-z]{6,16}$/i',$logname)){
                $this->echoJson(array('result' => 1, 'info' => "用户名只能是字母、数字、下划线、长度为6到16位"));
                exit;
            }else{
                $password=I("request.password");
                if(!preg_match('/^[_0-9a-z]{8,16}$/i',$password)){
                    $this->echoJson(array('result' => 1, 'info' => "密码只能是字母、数字、下划线、长度为8到16位"));
                    exit;
                }

                $Doctor = D('Doctor'); //查询用户是否存在
                $map['logname'] = $logname;
                $name = $Doctor->where($map)->find();
                if ($name) {
                    $this->echoJson(array('result' => 1, 'info' => "用户已存在"));
                    exit;
                } else if ($logname != " " && $password != " ") {  //==用户名不存在
                    $data['logname'] = $logname;
                    $data['create_time'] = time();
                    $data['password'] = md5($password);
                    $doctorId = $Doctor->add($data);
                    if ($doctorId) {
                        $this->echoJson(array('result' => 0, 'id' => $doctorId, 'info' => "注册成功"));
                        exit;
                    } else {
                        $this->echoJson(array('result' => 1, 'info' => "注册失败"));
                        exit;
                    }
                }
            }

        } else {
            $this->echoJson(array('result' => 1, 'info' => "密码或用户名错误"));
            exit;
        }
    }

    //======================APP登录信息===================
    public function login()
    {
        if (I("request.logname") != '' && I("request.password") != '') {
            $map['logname'] = I("request.logname");
            $map['password'] = md5(I("request.password"));
            $Doctor = D('Doctor');
            $r = $Doctor->where($map)->find();
            if ($r) {
                $r['img'] = (!empty($r['img'])) ? "http://img.cndoc.ivf-bb.com/" . $r['img'] : $r['img'];
                $r['sex'] = $r['sex'] == 0 ? "女" : "男";
                $r['auth_img'] = (!empty($r['auth_img'])) ?  "http://img.cndoc.ivf-bb.com/" . $r['auth_img'] : $r['auth_img'];
                $this->echoJson(array('result' => 0, 'info' => $r));
                exit;
            } else {//==用户名不存在的情况下===
                $this->echoJson(array('result' => 1, 'info' => "用户不存在"));
                exit;
            }

        } else {
            $this->echoJson(array('result' => 1, 'info' => "参数错误"));
            exit;
        }
    }

    //====================执行认证各种状态中的操作===============
    public function execution()
    {
        if (I("request.id") == '') {
            $this->echoJson(array("result" => 1, 'info' => '参数错误'));
            exit;
        } else {
            $id = I('request.id');
            $map['id'] = $id;
            $Doctor = D("Doctor");
            $info = $Doctor->where($map)->field("auth_status")->find();
            if (!$info) {
                $this->echoJson(array('result' => 1, 'info' => '未知错误'));
                exit;
            } else {
                if ($info['auth_status'] == 0) {
                    $this->echoJson(array('result' => 0, 'info' => $id));//到认证页面
                } else if ($info['auth_status'] == 1) {//如果权限状态为1时，把认证的信息呈现出来
                    $this->authlist();
                } elseif ($info['auth_status'] == 2) {//如果权限状态为2时，把认证成功的信息呈现出来
                    $this->authlist();
                } elseif ($info['auth_status'] == 3) {//如果权限状态为3时，把认证失败的信息呈现出来
                    $this->authlist();
                }
            }
        }
    }


    /*****************************注册成功需要进行认证，认证时会传我一注册的ID*************************/
    //http://121.40.78.46/tb/index.php?m=Home&c=App&a=getProvince&country=中国
    //country: 以数字:  0为中国，1为美国. //如果为汉字，暂也可
    //==========================================================================================
    //国家+省市==>医院
    //http://121.40.78.46/tb/index.php?m=Home&c=App&a=getHospital&country=中国&province=上海
    //country: 以数字:  0为中国，1为美国. //如果为汉字，暂也可

    //得到了国家和医院
    /********************************************************************************************************/
    public function uploadImage()
    {
        if (intval(I("request.id")) != '') {
            $Doctor = D("Doctor");
            $id = I("request.id");
            $status = $Doctor->where("id=" . $id)->getField('auth_status');
            if ($status == 0) {


                if ($_FILES['img'] != null) {

                    //七牛的上传
                    $setting=C('UPLOAD_SITEIMG_QINIU');
                    $setting['driverConfig']['domain']='img.cndoc.ivf-bb.com';
                    $setting['driverConfig']['bucket'] = 'imagecndoc';
                    // $setting['saveName'] = array ('uniqid', 'imagePYQ_');
//                    $setting['subName'] = 'imagecn_doc/'.date('Y-m-d',time());
                    $Upload = new \Think\Upload($setting);
                    $info = $Upload->upload($_FILES);
                    $t=  date('Y-m-d',time());
                    $name='';
                    foreach ($info as $v){
                        $name.=$t.'/'.$v['savename'];
                    }
                    //数据库保存数据
                    $data['img'] = $name;
                    $Doctor->where("id=" . $id)->save($data);
                    if ($Doctor) {
                        $imgDisplay = $Doctor->where("id=" . $id)->getField("img");
                        if ($imgDisplay) {
                            $imgDisplay = "http://img.cndoc.ivf-bb.com/" . $imgDisplay;
                            $this->echoJson(array('result' => 0, 'info' => $imgDisplay));
                        } else {
                            $this->echoJson(array('result' => 1, 'info' => '图片上传失败'));
                        }
                    }

                }


                if ($_FILES['auth_img'] != null) {

                    //七牛的上传
                    $setting=C('UPLOAD_SITEIMG_QINIU');
                    $setting['driverConfig']['domain']='img.cndoc.ivf-bb.com';
                    $setting['driverConfig']['bucket'] = 'imagecndoc';
                    // $setting['saveName'] = array ('uniqid', 'imagePYQ_');
//                        $setting['subName'] = 'imagecn_doc/'.date('Y-m-d',time());
                    $Upload = new \Think\Upload($setting);
                    $info = $Upload->upload($_FILES);
                    $t=  date('Y-m-d',time());
                    $name='';
                    foreach ($info as $v){
                        $name.=$t.'/'.$v['savename'];
                    }
                    //数据库保存数据
                    $data['auth_img'] = $name;
                    $Doctor->where("id=" . $id)->save($data);
                    if ($Doctor) {
                        $authDisplay = $Doctor->where("id=" . $id)->getField("auth_img");
                        if ($authDisplay) {
                            $auth_img = "http://img.cndoc.ivf-bb.com/" . $authDisplay;
                            $this->echoJson(array('result' => 0, 'info' => $auth_img));
                        } else {
                            $this->echoJson(array('result' => 1, 'info' => '图片上传失败'));
                        }
                    }

                }

            }
            //=======================上传认证图片=====================
        } else {
            $this->echoJson(array("result" => 1, "info" => '参数错误'));

        }
    }

    //=============================处理提交过来的表单=====================
    public function input()
    {
        if (!$id = intval(I('request.id'))) {
            $this->echoJson(array('result' => 1, 'info' => '参数错误'));
            exit;
        } else {
            $Doctor = D("Doctor");
            //================职称有中英文的两种，如果填写了中文就是中文,英文就是英文=====
            $data['title_cn'] = I("request.title_cn");//===中文职称==== Base64转码===
            $data['title_en'] = I("request.title_en"); //==英文职称====Base64转码====
            $data['speciality_en'] = I('request.speciality_en');
            $data['speciality_cn'] = I('request.speciality_cn');
            $data['abstract']='';
            //==========================必须确保数据都已经填写============================
            if (I("request.name") && I("request.hospital_id") && I("request.email") && I("request.document_number")) {
                $data['name'] = I("request.name");
                $data['sex'] = I("request.sex");
                $data['hospital_id'] = I("request.hospital_id");
                $data['document_number'] = I("request.document_number");
                $data['email'] = I("request.email");
                $data['auth_status'] = 1; //==把医生的状态手动赋值 也就是正在认证，====
                $image=$Doctor->where("id=".$id)->field('auth_img,img')->find();
                $auth_img=$image['auth_img'];//判断图片是否上传，如果未上传，提示信息
                $img=$image['img'];
                if($auth_img=="" || $img=="" ){
                    $this->echoJson(array('result' => 1, 'info' => "认证图片未传"));
                }else{
                    $result = $Doctor->where("id=" . $id)->save($data);
                    if ($result) {
                        $this->echoJson(array("result" => 0, 'info' => '提交成功'));
                    } else {
                        $this->echoJson(array('result' => 1, 'info' => "未知错误"));
                    }
                }
            } else {
                $this->echoJson(array('result' => 1, 'info' => '数据填写不完整'));
            }

        }
    }


    private function authlist()
    {
        if (!$id = intval(I('request.id'))) {
            $this->echoJson(array('result' => 1, 'info' => '参数错误'));
        }
        $Doctor = D("Doctor");
        $hospital = D("Hospital");
        $State = D("state");
        $Country = D("Country");

        $doctorInfo = $Doctor->where("id=" . $id)//得到医院的id
        ->field("id,name,hospital_id,auth_img,document_number,speciality_cn,speciality_en,name,email,sex,title_cn,title_en,auth_status")->find();
        $hid = $doctorInfo['hospital_id']; //获取医院名称和地区ID
        $hospitalInfo = $hospital->where("id=" . $hid)->field('zid,name')->find();
        $zid = $hospitalInfo['zid']; //地区名称 和国家ID
        $cityInfo = $State->where('id=' . $zid)->field("cid,name,en_name")->find();
        $cid = $cityInfo['cid'];  //取得国家信息
        $countryInfo = $Country->where('countryid=' . $cid)->field('countryname_en,countryname_cn')->find();
        $result = array();

        $result['hospital_name'] = $hospitalInfo['name'];
        $result['city_name'] = $cityInfo['name'];
        $result['city_name_en'] = $cityInfo['en_name'];
        $result['countryname'] = $countryInfo['countryname_cn'];
        $result['countryname_en'] = $countryInfo['countryname_en'];
        $result['id'] = $doctorInfo['id'];
        $result['doctor_name'] = $doctorInfo['name'];
        $result['auth_img'] = (!empty($doctorInfo['auth_img'])) ? "http://img.cndoc.ivf-bb.com/" . $doctorInfo['auth_img'] : $doctorInfo['auth_img'];
        $result['email'] = $doctorInfo['email'];
        $result['title_en'] = $doctorInfo['title_en'];
        $result['title_cn'] = $doctorInfo["title_cn"];
        $result['speciality_en'] = $doctorInfo['speciality_en'];
        $result['speciality_cn'] = $doctorInfo['speciality_cn'];
        $result['document_number'] = $doctorInfo['document_number'];
        $result['sex'] = $doctorInfo['sex'] == 0 ? "女" : "男";
        $result['en_sex'] = $doctorInfo['sex'] == 0 ? "Female" : "Male";
        $result['auth_status'] = $doctorInfo['auth_status'];
        $this->echoJson(array("result" => 0, 'auth_status' => $result['auth_status'], 'info' => $result));
    }

    //===========================retrieve找回密码======================================================
    public function retrieve()
    {
        //==============城市&医院的接口可以调之前的接口========
        if (I("request.hospital") != '' && I("request.document_number") != '') {
            $hospital = I("request.hospital");
            $document_number = I("request.document_number");
            $Doctor = D("Doctor");
            $map['hospital_id'] = $hospital;
            $map['document_number'] = $document_number;
            $res = $Doctor->where($map)->field('logname,id')->find();
            if ($res) {
                $this->echoJson(array('result' => 0, 'info' => $res));
            } else {
                $this->echoJson(array('result' => 1, 'info' => '未知错误'));
            }

        } else {
            $this->echoJson(array('result' => 1, 'info' => '参数错误'));
        }
    }

    //===========================重置密码============================
    public function reset(){
        if (I("request.password")!=""  && I("request.id")!="" && I("request.logname")!="") {//参数全部接收了才会执行下面的代码
            $Doctor = D("Doctor");
            $id = I("request.id");
            $map['id'] = $id;
            $logname=I("request.logname");

            //=====================如果状态为0，就是刚注册未认证，让用户重新注册======================
            $status = $Doctor->where($map)->getField("auth_status");//判断用户是否是验证中的状态，如果是执行代码
            if ($status == 2) {
                $lognameMap['logname']=$logname;
                $name = $Doctor->where($lognameMap)->find();
                if (!$name) {
                    $this->echoJson(array('result' => 1, 'info' => "用户名不存在"));
                    exit;
                }else {
                    $password = I('request.password');

                    if(!preg_match('/^[_0-9a-z]{8,16}$/i',$password)){
                        $this->echoJson(array('result' => 1, 'info' => "密码只能是字母、数字、下划线、长度为8到16位"));
                        exit;
                    }

                    $data['password'] = md5($password);
                    $data['logname'] = $logname;
                    $data['update_time'] = time();
                    $result = $Doctor->where($map)->save($data);
                    if ($result) {//密码修改写入成功时执行的
                        $this->echoJson(array('result' => 0, 'info' => '密码重置成功'));exit;
                    } else {// 密码写入失败时执行的
                        $this->echoJson(array('result' => 1, 'info' => '未知错误'));exit;
                    }
                }
            } else {//判断用户已经注册成功，用户没有执行验证的操作，让用重新注册
                $this->echoJson(array('result' => 1, 'info' => '账号未进行认证帐号的相关操作，请重新注册'));
            }

        } else {//如果参数接受不全，执行的操作。
            $this->echoJson(array('result' => 1, 'info' => '参数错误'));
        }
    }
}
